import React, { Component } from 'react';
import {
  StyleSheet, Text, View, Image, TouchableOpacity, Modal,
  ScrollView, PixelRatio, KeyboardAvoidingView, Platform, Keyboard, Switch,
} from "react-native";
import { style } from '../../../theme/style';
import { GLOBAL } from '../../../config/global';
import { FormItem } from '../../../components/form/formItem';
import { API, API_GENERATE } from '../../../config/api';
import RadioButton from '../../../components/form/radioButton';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import ProductSelect from '../../../containers/product/modals/ProductSelect';
import Dictionary from '../../../utils/dictionary';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import { purchaseTag } from './_components/common';
import { saleTag } from './_components/common';
import { Header } from 'react-navigation';
import MethodUtil from '../../../utils/MethodUtil';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import moment from 'moment';
import { OriginalAddress } from "../../../component/ui/OriginalAddress";
const currentMonth = moment().format('YYYYMM');
const scale = GLOBAL.SCALE;
const UD_PRICE_LIST = [
  {
    value: '升',
    key: '1',
  }, {
    value: '贴',
    key: '0',
  }
];
const quantityReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,999})?$/;
export class SinoNewOilProductFormPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let params = navigation.state.params || {};
    return {
      headerTitle: '商品信息',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
      headerTintColor: style.color.white,
      headerStyle: style.head.headerStyle,
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
      goodsModal: false,
      selectedGoods: [],
      quantityLabel: '', // 采购量/销售量文字

      priceFormlaModal: false,
      priceFormlaIndex: -1,
      priceFormlaList: [], // 结算价公式列表

      salePriceFormlaModal: false, // 闭口销售结算价公式
      salePriceFormlaIndex: -1,
      salePriceFormlaList: [],

      baseDateModal: false, // 基准日
      baseDateIndex: -1,
      baseDateList: [],

      switchOn: false,
      selectedKey: '1',
      saleSelectedKey: '1', // 闭口销售升贴水
      name: '',
      modalVisible: false //原产地
    }
    this.goodsInfo = {
      goodsId: '',
      goodsName: '',
      nakedPrice: '', // 一口价/暂定价
      quantity: '', // 采购量/销售量
      priceType: '1', // 1-一口价 2-暂定价
      priceFormlaId: '', // 结算价公式
      priceFormlaValue: '',
      baseDateSettle: '', // 基准日
      baseDateSettleName: '',
      udPrice: '', // 升贴水
      dutyRate: '', // 关税
      vatRate: '', // 增值税
    }
    this.showData = {
      havePlanQuantity: false, // 是否有计划量
      planQuantity: 0
    }
    this.result = null;
    this.polyolefinGoodsFlag = false;
    this.userInfo = {};
  }

  _getUserInfo = async () => {
    //获取用户信息
    let userInfo = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    if (userInfo) {
      userInfo = JSON.parse(userInfo);
    }
    return userInfo || {};
  }


  async componentWillMount() {
    let { sellerCompanyId, productIndex } = this.props.navigation.state.params || {};
    this.userInfo = await this._getUserInfo();
    this.isHuaxiao = sellerCompanyId == '154i6enqw0viqjhjqdni2jfim';
    this.productIndex = productIndex;
    await this.getDicts();
    this.initPage();
  }

  async getDicts() {
    let baseDateList = await Dictionary.get('BASE_DATE_SETTLE');
    this.setState({
      baseDateList
    })
  }

  initPage = () => {
    let { tCode, companyId, companyName, companyIdBuy, companyNameBuy, editData, organId, groupOnoff } = this.props.navigation.state.params;
    this.groupOnoff = groupOnoff || null;
    this.tCode = tCode;
    this.orderType = '';
    this.saleOrderType = '';
    this.companyId = companyId || companyIdBuy;

    this.companyName = companyName || companyNameBuy;
    this.companyIdBuy = companyIdBuy;
    this.companyNameBuy = companyNameBuy;
    this.organId = organId || '';
    switch (this.tCode) {
      case 'SINONEWP': // 采购-SINONEWP
        this.orderType = 'P';
        this.setState({
          quantityLabel: '采购量'
        })
        break;
      case 'SINONEWS': // 销售-SINONEWS
        this.orderType = 'S';
        this.setState({
          quantityLabel: '销售量'
        })
        break;
      case 'SINONEWC': // 闭口-SINONEWC
        this.orderType = 'P';
        this.saleOrderType = 'S';
        this.setState({
          quantityLabel: '数量'
        })
        let params = {
          nakedSalePrice: '',
          salePriceFormlaId: '',
          salePriceFormlaValue: '',
          saleUdPrice: '',
        }
        Object.assign(this.goodsInfo, params);
        break;
    }
    if (editData && editData.goodsId) {
      this.editInit(editData);
    }
  }

  // 编辑数据回填
  editInit = async (editData) => {
    this.setState({
      status: 'loading'
    })
    let { baseDateList, priceFormlaList, salePriceFormlaList } = this.state;
    let { goodsId, goodsName, nakedPrice, priceType, quantity, baseDateSettle, priceFormlaId, salePriceFormlaId, nakedSalePrice, udPrice, saleUdPrice, polyolefinGoodsFlag, dutyRate, vatRate, bizLineId, bizTeamId, makeAreaId, makePlace } = editData;
    this.goodsInfo = { goodsId, goodsName, nakedPrice, priceType, quantity, dutyRate, vatRate, bizLineId, bizTeamId, makeAreaId, makePlace };
    let selectIndex = {};
    let selectedKey = '1';
    let saleSelectedKey = '1';
    priceFormlaList = await this.getPriceFormulaList();
    if (this.tCode == 'SINONEWC') {
      salePriceFormlaList = await this.getSalePriceFormulaList();
      if (priceType == '1') {
        this.goodsInfo.nakedSalePrice = nakedSalePrice;
      }
    } else {
      this.getProductQuantity();
      // this.getGoodsQuantity();
    }
    // 暂定价回填
    if (priceType == '2') {
      // 基准日
      if (baseDateList && baseDateList.length > 0) {
        baseDateList.forEach((item, index) => {
          if (item.dictKey == baseDateSettle) {
            selectIndex.baseDateIndex = index;
            this.goodsInfo.baseDateSettle = item.dictKey;
            this.goodsInfo.baseDateSettleName = item.dictName;
          }
        })
      }

      // 结算价
      if (priceFormlaList && priceFormlaList.length > 0) {
        priceFormlaList.forEach((item, index) => {
          if (item.formulaId == priceFormlaId) {
            selectIndex.priceFormlaIndex = index;
            this.goodsInfo.priceFormlaId = item.formulaId;
            this.goodsInfo.priceFormlaValue = item.dictName;
          }
        })
      }
      // 闭口销售结算价
      if (this.tCode == 'SINONEWC') {
        if (salePriceFormlaList && salePriceFormlaList.length > 0) {
          salePriceFormlaList.forEach((item, index) => {
            if (item.formulaId == salePriceFormlaId) {
              selectIndex.salePriceFormlaIndex = index;
              this.goodsInfo.salePriceFormlaId = item.formulaId;
              this.goodsInfo.salePriceFormlaValue = item.dictName;
            }
          })
        }
      }

      selectedKey = (udPrice && udPrice > 0) ? '1' : '0';
      this.goodsInfo.udPrice = udPrice ? Math.abs(udPrice).toString() : '0'
      // 闭口数据回填
      if (this.tCode == 'SINONEWC') {
        saleSelectedKey = (saleUdPrice && saleUdPrice > 0) ? '1' : '0';
        this.goodsInfo.nakedSalePrice = nakedSalePrice ? Math.abs(nakedSalePrice).toString() : '0';
        this.goodsInfo.saleUdPrice = saleUdPrice ? Math.abs(saleUdPrice).toString() : '0';
      }
    }
    //一口价 回显
    this.polyolefinGoodsFlag = polyolefinGoodsFlag;
    this._changeFn();
    this._changeFn2();

    this.setState({
      status: 'data',
      switchOn: priceType == 2,
      selectedKey,
      saleSelectedKey,
      baseDateIndex: selectIndex.baseDateIndex,
      priceFormlaIndex: selectIndex.priceFormlaIndex,
      salePriceFormlaIndex: selectIndex.salePriceFormlaIndex,
      selectedGoods: [{ goodsId, goodsName }]
    })
  }

  // 保存
  saveGoodsInfo = () => {
    let { priceFormlaList, selectedKey, saleSelectedKey, salePriceFormlaList, switchOn } = this.state;
    if (this.goodsInfo.goodsId && this.goodsInfo.priceType == '2') {
      if (this.tCode != 'SINONEWC' && priceFormlaList.length == 0) {
        ToastUtil.showWarning('该商品没有维护价格公式');
        return;
      }
      if (this.tCode == 'SINONEWC' && (priceFormlaList.length == 0 || salePriceFormlaList.length == 0)) {
        ToastUtil.showWarning('该商品没有维护价格公式');
        return;
      }
    }
    // 闭口增加校验
    if (this.tCode == 'SINONEWC') {
      let lsResult = switchOn ? this.result2 : this.result;

      if (this.polyolefinGoodsFlag) {
        if (lsResult < 10) {
          ToastUtil.showWarning('商品销售盈利必须大于等于10美元');
          return;
        }
      } else {
        if (lsResult < 2) {
          ToastUtil.showWarning('商品销售盈利必须大于等于2美元');
          return;
        }
      }
    }

    // 表单验证
    if (!this.formVerify()) return;
    // 升贴水正负号
    this.goodsInfo.udPrice = selectedKey == '1' ? this.goodsInfo.udPrice : -this.goodsInfo.udPrice;
    if (this.tCode == 'SINONEWC') this.goodsInfo.saleUdPrice = saleSelectedKey == '1' ? this.goodsInfo.saleUdPrice : -this.goodsInfo.saleUdPrice;
    // 一口价的情况清除多余数据
    if (this.goodsInfo.priceType == '1') {
      let { goodsId, goodsName, nakedPrice, quantity, priceType, nakedSalePrice, dutyRate, vatRate, bizTeamId, bizLineId, makeAreaId, makePlace } = this.goodsInfo;
      callBackParams = {
        goodsId, goodsName, nakedPrice, quantity, priceType, dutyRate, vatRate, bizTeamId, bizLineId, makeAreaId, makePlace
      }
      if (this.tCode == 'SINONEWC') callBackParams.nakedSalePrice = nakedSalePrice;
    } else {
      callBackParams = this.goodsInfo
    }
    callBackParams.polyolefinGoodsFlag = this.polyolefinGoodsFlag;
    this.props.navigation.state.params.callBack(callBackParams);
    this.props.navigation.goBack();
  }
  formVerify = () => {
    let { quantityLabel } = this.state;
    let { goodsId, goodsName, quantity, nakedPrice, priceType, baseDateSettle, priceFormlaId, udPrice, nakedSalePrice, salePriceFormlaId, saleUdPrice, dutyRate, vatRate, makeAreaId } = this.goodsInfo;
    let { goodsList } = this.props.navigation.state.params;
    if (!goodsId) {
      ToastUtil.showWarning('请选择商品');
      return
    }
    let isIdentical = false;
    if (goodsList && goodsList.length) {
      goodsList.forEach((item, index) => {
        if (this.productIndex != index && goodsId == item.goodsId) {
          isIdentical = true;
        }
      })
    }
    if (isIdentical) {
      ToastUtil.showWarning(`商品信息${goodsName}重复添加！`);
      return
    }

    if (!quantity) {
      ToastUtil.showWarning(`请输入${quantityLabel}`);
      return
    }
    if (quantity <= 0) {
      ToastUtil.showWarning(`数量必须大于0`);
      return
    }
    if ((this.tCode == 'SINONEWS' && this.isHuaxiao) || this.tCode == 'SINONEWP') {
      if (!dutyRate) {
        ToastUtil.showWarning(`请输入关税比例`);
        return
      } else if (!quantityReg.test(dutyRate) && dutyRate != 0) {
        ToastUtil.showWarning(`请输入正确的关税数量`);
        return
      }
      if (!vatRate) {
        ToastUtil.showWarning(`请输入增值税比例`);
        return
      } else if (!quantityReg.test(vatRate) && vatRate != 0) {
        ToastUtil.showWarning(`请输入正确的增值税数量`);
        return
      }
    } else {
      this.goodsInfo.dutyRate = null;
      this.goodsInfo.vatRate = null;
    }

    // 敞口采购 采购量+当前已有库存必须小于等于敞口库存上限
    // if (this.tCode == 'SINONEWP' && this.showData.stockQuantity && this.showData.stockQuantityMax && this.showData.stockQuantity != 0 && this.showData.stockQuantityMax != 0 && (parseFloat(quantity) + parseFloat(this.showData.stockQuantity)) > parseFloat(this.showData.stockQuantityMax)) {
    //   ToastUtil.showWarning(`采购量+当前已有库存必须小于等于敞口库存上限`, 1500);
    //   return
    // }
    // 计划量管控
    if (this.checkPlanQuantity()) return;
    if ((this.tCode == 'SINONEWP' || this.tCode == 'SINONEWS') && priceType == 1) {
      if (!nakedPrice) {
        ToastUtil.showWarning('请输入一口价');
        return
      }
      if (nakedPrice == 0) {
        ToastUtil.showWarning('一口价必须大于零');
        return
      }
    }
    if (this.tCode == 'SINONEWC' && priceType == 1) {
      if (!nakedPrice) {
        ToastUtil.showWarning('请输入采购价');
        return
      }
      if (nakedPrice == 0) {
        ToastUtil.showWarning('采购价必须大于零');
        return
      }
      if (!nakedSalePrice) {
        ToastUtil.showWarning('请输入销售价');
        return
      }
      if (nakedSalePrice == 0) {
        ToastUtil.showWarning('销售价必须大于0');
        return
      }
    }
    // 暂定价-非闭口
    if ((this.tCode == 'SINONEWP' || this.tCode == 'SINONEWS') && priceType == 2) {
      if (!baseDateSettle) {
        ToastUtil.showWarning('选择基准日');
        return
      }
      if (!nakedPrice) {
        ToastUtil.showWarning('请输入暂定价');
        return
      }
      if (nakedPrice == 0) {
        ToastUtil.showWarning('暂定价必须大于0');
        return
      }
      if (!priceFormlaId) {
        ToastUtil.showWarning('请选择结算价公式');
        return
      }
      if (!udPrice) {
        ToastUtil.showWarning('请输入升贴水');
        return
      }
    }
    // 暂定价-闭口
    if (this.tCode == 'SINONEWC' && priceType == '2') {
      if (!baseDateSettle) {
        ToastUtil.showWarning('选择基准日');
        return
      }
      if (!nakedPrice) {
        ToastUtil.showWarning('请输入采购暂定价');
        return
      }
      if (nakedPrice == 0) {
        ToastUtil.showWarning('采购暂定价必须大于0');
        return
      }
      if (!priceFormlaId) {
        ToastUtil.showWarning('请选择采购结算价公式');
        return
      }
      if (!udPrice) {
        ToastUtil.showWarning('请输入采购升贴水');
        return
      }
      if (!nakedSalePrice) {
        ToastUtil.showWarning('请输入销售暂定价');
        return
      }
      if (nakedSalePrice == 0) {
        ToastUtil.showWarning('销售暂定价必须大于0');
        return
      }
      if (!salePriceFormlaId) {
        ToastUtil.showWarning('请选择销售结算价公式');
        return
      }
      if (!saleUdPrice) {
        ToastUtil.showWarning('请输入销售升贴水');
        return
      }
    }
    if (!makeAreaId) {
      ToastUtil.showWarning('请选择原产地');
      return
    }
    return true
  }

  // 打开商品选择弹窗
  openGoodsModal = () => {
    this.setState({
      goodsModal: true
    })
  }

  // 获取商品列表所需要的参数
  getGoodsListParams = () => {
    let params = {
      orderType: this.orderType,
      bizMode: 0 // 敞口-0  闭口-1
    };
    if (this.tCode == 'SINONEWC') {
      params.companyIdList = [this.companyId, this.companyIdBuy];
      params.bizMode = 1;
      params.orderType = '';
    } else {
      params.companyId = this.companyId;
    }
    return params;
  }

  // 选择商品
  selectGoods = (data) => {
    if (data.length > 0) {
      // 判断是不是聚烯烃
      if (data[0].polyolefinGoodsFlag && data[0].polyolefinGoodsFlag == '1') {
        this.polyolefinGoodsFlag = true;
      } else {
        this.polyolefinGoodsFlag = false;
      }
      let params = this.tCode == 'SINONEWC' ? {
        goodsId: data[0].goodsId,
        goodsName: data[0].goodsName,
        priceFormlaId: '',
        priceFormlaValue: '',
        salePriceFormlaId: '',
        salePriceFormlaValue: '',
      } : {
          goodsId: data[0].goodsId,
          goodsName: data[0].goodsName,
          priceFormlaId: '',
          priceFormlaValue: '',
        }
      Object.assign(this.goodsInfo, params);
      // 获取产品组
      this.goodsInfo.bizTeamId = data[0].goodsItem.bizTeamId;
      this.goodsInfo.bizLineId = data[0].goodsItem.bizLineId;
      this.getPriceFormulaList();
      if (this.tCode == 'SINONEWC') {
        this.getSalePriceFormulaList()
      } else {
        this.getProductQuantity();
        // this.getGoodsQuantity();
      }
      this.setState({
        goodsModal: false,
        priceFormlaIndex: -1,
        salePriceFormlaIndex: -1,
      })
    } else {
      this.setState({
        goodsModal: false
      })
    }
  }

  // 获取库存
  // getGoodsQuantity = async () => {
  //   let params = {
  //     organId: this.organId,
  //     goodsId: this.goodsInfo.goodsId,
  //   }
  //   let res = await HTTP.POST(API_GENERATE(API.GET_NEW_GOODS_QUANTITY), params);
  //   if (res) {
  //     this.showData.stockQuantity = res.stockQuantity; // 分公司敞口库存
  //     this.showData.stockQuantityMax = res.stockQuantityMax; // 敞口上限
  //   }
  // }

  // 获取计划量
  async getProductQuantity() {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    // isZxy P-1 S-0
    let params = {
      orderType: this.orderType,
      isUnite: 0,
      orderPlanMonth: currentMonth,
      goodsId: this.goodsInfo.goodsId,
      isZxy: this.orderType == 'P' ? 1 : 0,
      organId: this.organId || userInfo.organId
    }
    let res = await HTTP.POST(API_GENERATE(API.GET_GOODS_QUANTITY), params);
    if (res) {
      this.showData.remainPlanQuantity = res.remainPlanQuantity; // 计划量
      this.showData.stockQuantity = res.stockQuantity; // 分公司敞口库存
      this.showData.stockQuantityMax = res.stockQuantityMax; // 敞口上限
      this.showData.longQuantity = res.longQuantity; // 长约总量
      this.showData.remainLongQuantity = res.remainLongQuantity; // 剩余量
      this.checkPlanQuantity()
    }
    this.setState({ status: 'data' })
    // let checkUrl = this.orderType == 'P' ? API.CHECK_ZXY_PLAN_QUANTITY : API.CHECK_PLAN_QUANTITY;
    // let getUrl = this.orderType == 'P' ? API.GET_ZXY_PLAN_QUANTITY : (this.isHuaxiao ? API.GET_HUAXIAO_PLAN_QUANTITY : API.GET_PLAN_QUANTITY);
    // let params = {
    //   goodsId: this.goodsInfo.goodsId,
    //   orderType: this.orderType,
    //   bizType: 'OWN'
    // }
    // let checkRes = await HTTP.POST(API_GENERATE(checkUrl), params)
    // // 如果提报了计划量，则开始获取
    // if (checkRes && checkRes.check) {
    //   let { goodsList, orderId, editData } = this.props.navigation.state.params;
    //   // 超过一个商品需要传orderId
    //   params.orderId = (goodsList.length == 0 || (goodsList.length == 1 && editData)) ? null : orderId;
    //   let getRes = await HTTP.POST(API_GENERATE(getUrl), params);
    //   if (getRes) {
    //     this.showData.havePlanQuantity = true;
    //     this.showData.planQuantity = getRes.weight;
    //   }
    // } else {
    //   this.showData.havePlanQuantity = false;
    //   this.showData.planQuantity = '';
    // }
    // this.setState({
    //   ls: true
    // }, () => { this.checkPlanQuantity() })
  }

  // 计划量管控
  // orderType == 'P' 中新油  CHECK_ZXY_PLAN_QUANTITY（确认是否提报接口）  GET_ZXY_PLAN_QUANTITY（获取计划量）
  // orderType == 'S'  && 客户id != 化销   CHECK_PLAN_QUANTITY（确认是否提报接口） GET_HUAXIAO_PLAN_QUANTITY(获取计划量 客户id == 化销)  GET_PLAN_QUANTITY(获取计划量 客户id != 化销)
  checkPlanQuantity = () => {
    if (this.tCode == 'SINONEWC') return
    // if (this.orderType == 'P' || (this.orderType == 'S' && !this.isHuaxiao)) {
    //   if ((this.showData.remainPlanQuantity || this.showData.remainPlanQuantity == 0) && this.goodsInfo.quantity && (parseFloat(this.goodsInfo.quantity) > parseFloat(this.showData.remainPlanQuantity))) {
    //     ToastUtil.showWarning(`${this.orderType == 'P' ? '采购量' : '销售量'}大于计划量，请调整后提交`, 1500);
    //     return true
    //   }
    // }
  }

  // 获取结算价公式列表
  async getPriceFormulaList() {
    if (this.goodsInfo.goodsId) {
      this.setState({
        status: 'loading'
      })
      let responseData = await HTTP.POST(API_GENERATE(API.GET_PRICE), {
        goodsId: this.goodsInfo.goodsId,
        orderType: this.orderType
      });
      if (!responseData) return resolve()
      responseData.map((item, index) => {
        item.dictName = item.formulaName;
      });
      this.setState({
        status: 'data',
        priceFormlaList: responseData,
      })
      return new Promise((resolve, reject) => {
        resolve(responseData);
      })
    }
  }

  // 闭口销售结算价公式
  async getSalePriceFormulaList() {
    if (this.goodsInfo.goodsId) {
      this.setState({
        status: 'loading'
      })
      let responseData = await HTTP.POST(API_GENERATE(API.GET_PRICE), {
        goodsId: this.goodsInfo.goodsId,
        orderType: this.saleOrderType
      });
      if (!responseData) return resolve()
      responseData.map((item, index) => {
        item.dictName = item.formulaName;
      });
      this.setState({
        status: 'data',
        salePriceFormlaList: responseData,
      })
      return new Promise((resolve, reject) => {
        resolve(responseData);
      })
    }
  }

  // 切换价格类型
  switchChange = (val) => {
    let { priceFormlaList, salePriceFormlaList } = this.state;
    this.goodsInfo.priceType = val ? '2' : '1';
    this.setState({
      switchOn: val
    }, () => {
      console.log('val', val, this.result)
    })
    if (this.goodsInfo.goodsId && val) {
      if ((this.tCode != 'SINONEWC' && priceFormlaList.length == 0) || (this.tCode == 'SINONEWC' && (priceFormlaList.length == 0 || salePriceFormlaList.length == 0))) {
        ToastUtil.showWarning('该商品没有维护价格公式');
      }
    }
  }

  // 选择基准日
  baseDateCallBack = (index) => {
    let { baseDateList } = this.state;
    this.goodsInfo.baseDateSettle = baseDateList[index].dictKey;
    this.goodsInfo.baseDateSettleName = baseDateList[index].dictName;
    this.setState({
      baseDateModal: false,
      baseDateIndex: index,
    })
  }

  // 选择结算价
  priceFormlaCallback = (index) => {
    let { priceFormlaList } = this.state;
    this.goodsInfo.priceFormlaId = priceFormlaList[index].formulaId;
    this.goodsInfo.priceFormlaValue = priceFormlaList[index].formulaName;
    this.setState({
      priceFormlaModal: false,
      priceFormlaIndex: index,
    })
  }

  // 闭口结算价公式选择
  salePriceFormlaCallback = (index) => {
    let { salePriceFormlaList } = this.state;
    this.goodsInfo.salePriceFormlaId = salePriceFormlaList[index].formulaId;
    this.goodsInfo.salePriceFormlaValue = salePriceFormlaList[index].formulaName;
    this.setState({
      salePriceFormlaModal: false,
      salePriceFormlaIndex: index,
    })
  }

  // 一口价 盈利计算
  _changeFn = () => {
    this.result = MethodUtil.countObj.subtract(this.goodsInfo.nakedSalePrice, this.goodsInfo.nakedPrice);
    this.result = MethodUtil.countObj.multiply(this.result, this.goodsInfo.quantity)
    this.setState({
      ls: true
    })
  }

  // 暂定价 盈利计算
  _changeFn2 = () => {
    let { selectedKey, saleSelectedKey } = this.state;
    let lsBuyPrice = this.goodsInfo.udPrice;
    let lsSalePrice = this.goodsInfo.saleUdPrice;
    lsBuyPrice = selectedKey == '1' ? lsBuyPrice : -lsBuyPrice;
    if (this.tCode == 'SINONEWC') lsSalePrice = saleSelectedKey == '1' ? lsSalePrice : -lsSalePrice;

    this.result2 = MethodUtil.countObj.subtract(lsSalePrice, lsBuyPrice);
    this.result2 = MethodUtil.countObj.multiply(this.result2, this.goodsInfo.quantity);
    this.setState({
      ls: true
    })
  }
  // 关税
  addCustoms = (name) => {
    this.goodsInfo.dutyRate = name;
  }
  // 增值税
  addedvalueTax = (name) => {
    this.goodsInfo.vatRate = name;
  }

  //原产地-回调
  _addressCallback = (addressData) => {
    console.log("addressData", addressData)
    this.goodsInfo.makeAreaId = addressData.makeAreaId;
    this.goodsInfo.makePlace = addressData.makePlace;
    this.setState({
      ls: true
    })
  }

  render() {
    let { status, switchOn, goodsModal, selectedGoods, quantityLabel,
      baseDateModal, baseDateIndex, baseDateList, selectedKey, saleSelectedKey,
      priceFormlaModal, priceFormlaIndex, priceFormlaList, salePriceFormlaModal, salePriceFormlaIndex, salePriceFormlaList, modalVisible } = this.state;
    let { goodsId, goodsName, quantity, nakedPrice, nakedSalePrice, udPrice, saleUdPrice, baseDateSettleName, priceFormlaValue, salePriceFormlaValue, dutyRate, vatRate, makePlace } = this.goodsInfo;
    return (
      <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={Header.HEIGHT + 40}>
        <ScrollView keyboardShouldPersistTaps={'handled'}>

          {/* 公司名称 */}
          {this.tCode == 'SINONEWC' ?
            (<FormItem type={'input'}
              border
              editable={false}
              value={''}
              tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : ''}
              label={this.companyNameBuy} />) : null
          }

          <FormItem type={'input'}
            border
            editable={false}
            value={''}
            tagLogo={this.tCode === 'SINONEWC' ? saleTag : ''}
            label={this.companyName} />

          {/* 选择商品 */}
          <FormItem type={'select'}
            border
            label='商品名'
            value={goodsName}
            placeHolder='请选择商品'
            handleCallBack={() => { this.openGoodsModal() }} />

          {/* 数量 */}
          <FormItem type={'input'}
            border
            label={quantityLabel}
            placeHolder='请输入'
            value={quantity}
            keyboardType='numeric'
            handleCallBack={(text) => { this.goodsInfo.quantity = text }}
            onBlurFn={() => {
              if (this.goodsInfo.goodsId && this.tCode != 'SINONEWC' && this.goodsInfo.quantity && this.goodsInfo.quantity.length > 0) {
                this.checkPlanQuantity()
              }
              if (switchOn) {
                this._changeFn2()
              } else {
                this._changeFn()
              }



            }}
            rightText={'吨'} />

          {
            (this.goodsInfo.goodsId && (this.tCode == 'SINONEWP' || (this.tCode == 'SINONEWS' && !this.isHuaxiao))) ? (
              <View style={{ paddingLeft: 20 * scale }}>
                <Text style={{ color: '#F66464', fontSize: 13 * scale, marginTop: 8 * scale }}>
                  {/* {`当月剩余可${this.tCode == 'SINONEWP' ? '采' : '售'}计划量：${this.showData.remainPlanQuantity || '--'}吨；`} */}
                  {
                    this.tCode == 'SINONEWP' ? (
                      <Text>
                        分公司敞口库存：{this.showData.stockQuantity || '--'}吨；
                        敞口上限：{this.showData.stockQuantityMax || '--'}吨；
                      </Text>
                    ) : null
                  }
                </Text>
              </View>
            ) : null
          }

          {/* 一口价/暂定价切换 */}
          <View style={styles.priceTypeWrap}>
            <Text style={[styles.priceTypeValue, switchOn ? '' : styles.switchOn]}>一口价</Text>
            <Switch
              style={styles.switchBtn}
              onTintColor='#CCDDF2'  //开关打开时的背景颜色
              thumbTintColor='#0E7FFD' //开关上原形按钮的颜色
              tintColor='#CCDDF2' //关闭时背景颜色
              value={switchOn}//默认状态
              onValueChange={(val) => { this.switchChange(val) }}
            />
            <Text style={[styles.priceTypeValue, switchOn ? styles.switchOn : '']}>暂定价</Text>
          </View>
          {/* 一口价/暂定价显示不同内容 */}
          {
            switchOn ? (
              <View>
                <FormItem type={'select'}
                  border
                  label='基准日'
                  value={baseDateSettleName}
                  placeHolder={'请选择基准日'}
                  handleCallBack={() => { this.setState({ baseDateModal: true }) }} />

                <FormItem type={'input'}
                  border
                  label={switchOn ? '暂定价' : ''}
                  placeHolder='请输入'
                  keyboardType='numeric'
                  value={nakedPrice}
                  handleCallBack={(text) => { this.goodsInfo.nakedPrice = text }}
                  rightText={'美元/吨'}
                  tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : ''}
                />

                <FormItem type={'select'}
                  label='结算价'
                  value={priceFormlaValue}
                  placeHolder={'请选择价格公式'}
                  tagLogo={this.tCode === 'SINONEWC' ? purchaseTag : ''}
                  handleCallBack={() => {
                    if (goodsId) {
                      this.setState({ priceFormlaModal: true })
                    } else {
                      ToastUtil.showWarning('请先选择商品')
                    }
                  }} />

                <View style={styles.udPriceWrap}>
                  <View style={styles.radioGroup}>
                    {
                      UD_PRICE_LIST.map((item, index) => {
                        return (
                          <RadioButton key={index}
                            radioValue={item.value}
                            radioKey={item.key}
                            selectedKey={selectedKey}
                            selectedChange={(key) => {
                              this.setState({
                                selectedKey: key
                              }, () => {
                                this._changeFn2();
                              })
                            }} />
                        )
                      })
                    }
                  </View>
                  <FormItem type={'input'}
                    border
                    placeHolder='请输入'
                    keyboardType='numeric'
                    value={udPrice}
                    handleCallBack={(text) => { this.goodsInfo.udPrice = text; this._changeFn2() }}
                    rightText={'美元/吨'} />
                </View>

                {
                  this.tCode == 'SINONEWC' ? (
                    <View>
                      <FormItem type={'input'}
                        border
                        label={switchOn ? '暂定价' : ''}
                        placeHolder='请输入'
                        keyboardType='numeric'
                        value={nakedSalePrice}
                        handleCallBack={(text) => { this.goodsInfo.nakedSalePrice = text; }}
                        rightText={'美元/吨'}
                        tagLogo={this.tCode === 'SINONEWC' ? saleTag : ''}
                      />

                      <FormItem type={'select'}
                        label='结算价'
                        value={salePriceFormlaValue}
                        placeHolder={'请选择价格公式'}
                        tagLogo={this.tCode === 'SINONEWC' ? saleTag : ''}
                        handleCallBack={() => {
                          if (goodsId) {
                            this.setState({ salePriceFormlaModal: true })
                          } else {
                            ToastUtil.showWarning('请先选择商品')
                          }
                        }} />
                      <View style={styles.udPriceWrap}>
                        <View style={styles.radioGroup}>
                          {
                            UD_PRICE_LIST.map((item, index) => {
                              return (
                                <RadioButton key={index}
                                  radioValue={item.value}
                                  radioKey={item.key}
                                  selectedKey={saleSelectedKey}
                                  selectedChange={(key) => {
                                    this.setState({
                                      saleSelectedKey: key
                                    }, () => {
                                      this._changeFn2();
                                    })
                                  }} />
                              )
                            })
                          }
                        </View>
                        <FormItem type={'input'}
                          border
                          placeHolder='请输入'
                          keyboardType='numeric'
                          value={saleUdPrice}
                          handleCallBack={(text) => { this.goodsInfo.saleUdPrice = text; this._changeFn2() }}
                          rightText={'美元/吨'} />
                      </View>
                    </View>
                  ) : null
                }
                {this.result2 || this.result2 == 0 ? (<Text style={styles.resulte}>{this.result2 > 0 ? '盈利' : '亏损'}<Text style={styles.resulteColor}>{Math.abs(this.result2)}</Text>美元</Text>) : null}
              </View>
            ) : (this.tCode === 'SINONEWC') ? (
              <View>
                <FormItem type={'input'}
                  border
                  label={'一口价'}
                  placeHolder='请输入'
                  keyboardType='numeric'
                  value={nakedPrice}
                  handleCallBack={(text) => { this.goodsInfo.nakedPrice = text; this._changeFn() }}
                  rightText={'美元/吨'}
                  tagLogo={purchaseTag}
                />

                <FormItem type={'input'}
                  border
                  label={'一口价'}
                  placeHolder='请输入'
                  keyboardType='numeric'
                  value={nakedSalePrice}
                  handleCallBack={(text) => { this.goodsInfo.nakedSalePrice = text; this._changeFn() }}
                  rightText={'美元/吨'}
                  tagLogo={saleTag}
                />
                {
                  this.result || this.result == 0 ? (<Text style={styles.resulte}>{this.result > 0 ? '盈利' : '亏损'}<Text style={styles.resulteColor}>{Math.abs(this.result)}</Text>美元</Text>) : null
                }
              </View>
            ) : (
                  <FormItem type={'input'}
                    border
                    placeHolder='请输入'
                    keyboardType='numeric'
                    value={nakedPrice}
                    handleCallBack={(text) => { this.goodsInfo.nakedPrice = text }}
                    rightText={'美元/吨'} />
                )
          }
          {(this.tCode == 'SINONEWS' && this.isHuaxiao) || this.tCode == 'SINONEWP' ?
            <View>
              <FormItem
                border
                label='关税'
                type='input'
                value={dutyRate}
                keyboardType='numeric'
                rightText='%'
                placeHolder='请输入'
                handleCallBack={(str) => { this.addCustoms(str) }} />
              <FormItem
                border
                label='增值税'
                type='input'
                value={vatRate}
                keyboardType='numeric'
                rightText='%'
                placeHolder='请输入'
                handleCallBack={(str) => { this.addedvalueTax(str) }} />
            </View>
            : null
          }
          <FormItem type={'select'}
            required
            border
            label='原产地'
            value={makePlace}
            placeHolder='请选择原产地'
            handleCallBack={() => { this.setState({ modalVisible: true }) }} />
          <View style={styles.btnWrap}>
            <TouchableOpacity activeOpacity={.8} style={styles.saveBtn} onPress={() => { this.saveGoodsInfo() }}>
              <Text style={styles.saveText}>保存</Text>
            </TouchableOpacity>
          </View>

        </ScrollView>

        {/* 商品选择弹窗 */}
        {
          goodsModal ? (<ProductSelect
            isZXY={true}
            confirmPress={this.selectGoods}
            cancelPress={() => { this.setState({ goodsModal: false }) }}
            sendData={this.getGoodsListParams()}
            mainCheckData={selectedGoods}
            groupOnoff={this.groupOnoff}
            modalVisible={goodsModal} />) : null
        }
        {/* 基准日 */}
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={baseDateIndex} title="基准日" listData={baseDateList} selectCallBack={this.baseDateCallBack} />
        )} isVisible={baseDateModal} closeCallballFn={() => { this.setState({ baseDateModal: false }) }} />
        {/* 结算价公式 */}
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={priceFormlaIndex} title="结算价" listData={priceFormlaList} selectCallBack={this.priceFormlaCallback} />
        )} isVisible={priceFormlaModal} closeCallballFn={() => { this.setState({ priceFormlaModal: false }) }} />
        {/* 闭口销售结算价公式 */}
        <Common type="modal" demoData={(
          <Common type="listRadio" selectIndex={salePriceFormlaIndex} title="结算价" listData={salePriceFormlaList} selectCallBack={this.salePriceFormlaCallback} />
        )} isVisible={salePriceFormlaModal} closeCallballFn={() => { this.setState({ salePriceFormlaModal: false }) }} />
        {
          status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
        }
        {
          modalVisible ? <OriginalAddress
            modalVisible={modalVisible}
            closeModal={() => { this.setState({ modalVisible: false }) }}
            params={{ tradeType: 'O' }}
            addressCallback={this._addressCallback}
          /> : null
        }
      </KeyboardAvoidingView >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.white,
  },
  statusStyle: {
    flex: 1,
    position: 'absolute',
    height: '100%',
    width: '100%',
    top: 0,
    left: 0,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center'
  },
  entpriseWrap: {
    height: 56 * scale,
    justifyContent: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#E3E7F0',
    paddingLeft: 23 * scale,
  },
  udPriceWrap: {
    position: 'relative',
  },
  radioGroup: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'absolute',
    top: 14 * scale,
    left: 23 * scale,
    zIndex: 9
  },
  priceTypeWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
    marginTop: 11 * scale,
    marginBottom: 26 * scale,
    marginRight: 24.5 * scale,
  },
  switchBtn: {
    marginLeft: 6 * scale,
    marginRight: 6 * scale,
  },
  priceTypeValue: {
    fontSize: 14 * scale,
    color: '#848A96'
  },
  switchOn: {
    color: '#000'
  },
  btnWrap: {
    marginTop: 40 * scale,
    alignItems: 'center',
  },
  saveBtn: {
    height: 42 * scale,
    backgroundColor: '#0E7FFD',
    borderRadius: 6 * scale,
    width: '80%',
  },
  saveText: {
    lineHeight: 42 * scale,
    fontSize: 16 * scale,
    textAlign: 'center',
    color: '#fff',
  },
  resulte: {
    textAlign: 'right',
    paddingTop: 5 * scale,

    paddingRight: 8 * scale
  },
  resulteColor: {
    color: style.color.lightRed,
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    fontWeight: 'bold'
  }
})